import { login, logout, getInfo } from '@/api/system/auth'
import {
  getToken,
  setToken,
  removeToken,
  setEnterpriseName,
  getEnterpriseName,
  getQrCodeUrl,
  setQrCodeUrl
} from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    enterpriseName: getEnterpriseName(),
    qrCodeUrl: getQrCodeUrl()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    sessionStorage.setItem('authorization', token)
  },
  SET_USERNAME: (state, username) => {
    sessionStorage.setItem('username', username)
  },
  SET_MENU: (state, menus) => {
    sessionStorage.setItem('menus', menus)
  },
  SET_PERMISSIONS: (state, permissions) => {
    sessionStorage.setItem('permissions', permissions)
  },
  SET_ENTERPRISE_NAME: (state, enterpriseName) => {
    sessionStorage.setItem('enterpriseName', enterpriseName)
  },
  SET_QR_CODE_URL: (state, qrCodeUrl) => {
    sessionStorage.setItem('qrCodeUrl', qrCodeUrl)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verifyCode, sessionId } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, verifyCode: verifyCode, sessionId: sessionId }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        setEnterpriseName(data.enterpriseName)
        setQrCodeUrl(data.qrCodeUrl)
        commit('SET_USERNAME', data.username)
        commit('SET_ENTERPRISE_NAME', data.enterpriseName)
        commit('SET_QR_CODE_URL', data.qrCodeUrl)
        commit('SET_MENU', JSON.stringify(data.menus))
        commit('SET_PERMISSIONS', data.permissions)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        sessionStorage.clear()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

